package com.hainatong.shiphelper;

import java.io.File;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import android.graphics.BitmapFactory;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.bumptech.glide.Glide;
import com.hainatong.shiphelper.databinding.ActivitySwitchBinding;
import com.hainatong.shiphelper.mainhome.adapter.ExamineStepAdapter;
import com.hainatong.shiphelper.mainhome.adapter.ProcessStepAdapter;
import com.hainatong.shiphelper.mainhome.adapter.TimeLineAdapter;
import com.hainatong.shiphelper.mainhome.entity.ExamineStepBean;
import com.hainatong.shiphelper.pictureselector.PictureBean;
import com.hainatong.shiphelper.pictureselector.PictureSelector;
import com.hainatong.shiphelper.widget.luban.CompressionPredicate;
import com.hainatong.shiphelper.widget.luban.Luban;
import com.hainatong.shiphelper.widget.luban.OnCompressListener;
import com.hainatong.shiphelper.widget.luban.OnRenameListener;
import com.hainatong.shiphelper.widget.stepview.bean.StepBean;
import com.hainatong.mvvmbase.base.BaseMvvmActivity;
import com.hainatong.mvvmbase.base.NoViewModel;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class SwitchActivity extends BaseMvvmActivity<ActivitySwitchBinding, NoViewModel>
{

    public static void start(Context context)
    {
        Intent start = new Intent(context ,SwitchActivity.class);
        context.startActivity( start );
    }

    @Override
    protected int getLayoutId()
    {
        return R.layout.activity_switch;
    }

    @Override
    protected int getBindingVariable() {
        return 0;
    }

    @Override
    protected void initView()
    {
        initPermission();
        viewDataBinding.btnSelect.setOnClickListener(view -> {
            //选择图片
            PictureSelector.create(this, PictureSelector.SELECT_REQUEST_CODE)
                    .selectPicture(false);
        });
    }

    @Override
    protected void initData()
    {

        // 流程步骤 demo
        List<StepBean> stepsBeanList = new ArrayList<>();
        StepBean stepBean0 = new StepBean("接单",1);
        StepBean stepBean1 = new StepBean("打包",1);
        StepBean stepBean2 = new StepBean("出发",0);
        StepBean stepBean3 = new StepBean("送单",-1);
        StepBean stepBean4 = new StepBean("完成",-1);
        StepBean stepBean5 = new StepBean("支付",-1);
        stepsBeanList.add(stepBean0);
        stepsBeanList.add(stepBean1);
        stepsBeanList.add(stepBean2);
        stepsBeanList.add(stepBean3);
        stepsBeanList.add(stepBean4);
        stepsBeanList.add(stepBean5);
        viewDataBinding.hStepview.setStepViewTexts(stepsBeanList)
                //set textSize
                .setTextSize(16)
                //设置StepsViewIndicator完成线的颜色
                .setStepsViewIndicatorCompletedLineColor(ContextCompat.getColor(getBaseContext(), android.R.color.white))
                //设置StepsViewIndicator未完成线的颜色
                .setStepsViewIndicatorUnCompletedLineColor(ContextCompat.getColor(getBaseContext(), R.color.uncompleted_text_color))
                //设置StepsView text完成线的颜色
                .setStepViewComplectedTextColor(ContextCompat.getColor(getBaseContext(), android.R.color.white))
                //设置StepsView text未完成线的颜色
                .setStepViewUnComplectedTextColor(ContextCompat.getColor(getBaseContext(), R.color.uncompleted_text_color))
                //设置StepsViewIndicator CompleteIcon
                .setStepsViewIndicatorCompleteIcon(ContextCompat.getDrawable(getBaseContext(), R.mipmap.complted))
                //设置StepsViewIndicator DefaultIcon
                .setStepsViewIndicatorDefaultIcon(ContextCompat.getDrawable(getBaseContext(), R.mipmap.default_icon))
                //设置StepsViewIndicator AttentionIcon
                .setStepsViewIndicatorAttentionIcon(ContextCompat.getDrawable(getBaseContext(), R.mipmap.attention));



        //正向画流程，默认是反向   需要 VerticalStepView.reverseDraw(false)；
        List<String> list0 = new ArrayList<>();
        list0.add("您已提交定单，等待系统确认");
        list0.add("您的商品需要从外地调拨，我们会尽快处理，请耐心等待");
        list0.add("您的订单已经进入亚洲第一仓储中心1号库准备出库");
        list0.add("您的订单预计6月23日送达您的手中，618期间促销火爆，可能影响送货时间，请您谅解，我们会第一时间送到您的手中");
        list0.add("您的订单已打印完毕");
        list0.add("您的订单已拣货完成");
        list0.add("扫描员已经扫描");
        list0.add("打包成功");
        list0.add("您的订单在京东【华东外单分拣中心】发货完成，准备送往京东【北京通州分拣中心】");
        list0.add("您的订单在京东【北京通州分拣中心】分拣完成");
        list0.add("您的订单在京东【北京通州分拣中心】发货完成，准备送往京东【北京中关村大厦站】");
        list0.add("您的订单在京东【北京中关村大厦站】验货完成，正在分配配送员");
        list0.add("配送员【包牙齿】已出发，联系电话【130-0000-0000】，感谢您的耐心等待，参加评价还能赢取好多礼物哦");
        list0.add("感谢你在京东购物，欢迎你下次光临！");

        viewDataBinding.vStepView1.setStepsViewIndicatorComplectingPosition(list0.size() - 2)//设置完成的步数
                .reverseDraw(false)//default is true
                .setTextSize(14)
                //.setLinePaddingProportion(0.85f)//设置indicator线与线间距的比例系数
                .setStepViewTexts(list0)//总步骤
                //设置StepsViewIndicator完成线的颜色
                .setStepsViewIndicatorCompletedLineColor(ContextCompat.getColor(this, android.R.color.white))
                //设置StepsViewIndicator未完成线的颜色
                .setStepsViewIndicatorUnCompletedLineColor(ContextCompat.getColor(this, R.color.uncompleted_text_color))
                //设置StepsView text完成线的颜色
                .setStepViewComplectedTextColor(ContextCompat.getColor(this, android.R.color.white))
                //设置StepsView text未完成线的颜色
                .setStepViewUnComplectedTextColor(ContextCompat.getColor(this, R.color.uncompleted_text_color))
                //设置StepsViewIndicator CompleteIcon
                .setStepsViewIndicatorCompleteIcon(ContextCompat.getDrawable(this, R.mipmap.complted))
                //设置StepsViewIndicator DefaultIcon
                .setStepsViewIndicatorDefaultIcon(ContextCompat.getDrawable(this, R.mipmap.default_icon))
                //设置StepsViewIndicator AttentionIcon
                .setStepsViewIndicatorAttentionIcon(ContextCompat.getDrawable(this, R.mipmap.attention));


        TimeLineAdapter lineAdapter = TimeLineAdapter.newInstance( new String[]{"2020-10-20 09:00","2020-10-25 09:00"} );
        viewDataBinding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
        viewDataBinding.recyclerview.hasFixedSize();
        viewDataBinding.recyclerview.setAdapter( lineAdapter );

        ProcessStepAdapter stepAdapter = ProcessStepAdapter.newInstance(new String[]{"大副","船长","岸基"}, new String[]{"大副","船长","岸基"} );
        viewDataBinding.recyclerview2.setLayoutManager(new LinearLayoutManager(this));
        viewDataBinding.recyclerview2.hasFixedSize();
        viewDataBinding.recyclerview2.setAdapter( stepAdapter );



        ExamineStepAdapter examineAdapter = new ExamineStepAdapter();

        List<ExamineStepBean> stepList = new ArrayList<>();
        ExamineStepBean step = new ExamineStepBean();
        step.setStatus( ExamineStepBean.StepStatus.START );
        step.setActiveTime( "2020-08-20  09:00" );
        step.setStepName("发起申请");
        step.setSubName("王磊");
        stepList.add( step );




        examineAdapter.setList( stepList );
        viewDataBinding.recyclerview3.setLayoutManager(new LinearLayoutManager(this));
        viewDataBinding.recyclerview3.hasFixedSize();
        viewDataBinding.recyclerview3.setAdapter( stepAdapter );

    }

    @Override
    protected void onRetryBtnClick() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        /* 选择图片 结果回调*/
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE)
        {
            if (data != null)
            {
                PictureBean pictureBean = data.getParcelableExtra(PictureSelector.PICTURE_RESULT);
                Log.e("PictureSelector","是否裁剪: " + pictureBean.isCut());
                Log.e("PictureSelector","原图地址: " + pictureBean.getPath());
                Log.e("PictureSelector","图片 Uri: " + pictureBean.getUri());

                File imgFile = new File( pictureBean.getPath() );

                withRx( imgFile );
                //withLs( imgFile );

                if (false)
                {
                    //BitmapFactory.decodeFile(pictureBean.getPath())

                    //图片文件
                    //File file = new File(pictureBean.getPath());

                }
                else
                {
                    //HeadImg.setImageURI(pictureBean.getUri());
                }

                //使用 Glide 加载图片
                /*Glide.with(this)
                        .load(pictureBean.isCut() ? pictureBean.getPath() : pictureBean.getUri())
                        .apply(RequestOptions.centerCropTransform()).into(mIvImage);*/

                //实际开发中将图片上传到服务器成功后需要删除全部缓存图片（即裁剪后的无用图片）
                //FileUtils.deleteAllCacheImage(this);
            }
        }
    }

    private void goCheckPicture( String img)
    {

        PictureCheckActivity.start(this ,img );
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void initPermission()
    {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x0001);
        }
    }

    private <T> void withRx(final File photo)
    {

        StringBuilder sb = new StringBuilder();
        int[] oWH = computeSize( photo );


        sb.append( String.format( "原图参数：%d*%d, %dk",  oWH[0],oWH[1] ,photo.length() >> 10) );
        sb.append("\n");

        Disposable mDispo =
        Flowable.just(photo)
                .observeOn(Schedulers.io())
                .map(file -> {
                    MessageDigest md = MessageDigest.getInstance("MD5");
                    md.update(file.getAbsolutePath().getBytes());
                    String fileName = new BigInteger(1, md.digest()).toString(32);

                    return  Luban.with(SwitchActivity.this)
                            .setTargetDir(getPath())
                            .load( file )
                            .setFocusAlpha(false)
                            .get(file.getAbsolutePath());
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnError( throwable->{
                    Log.e(TAG, throwable.getMessage());
                } )
                .onErrorResumeNext(Flowable.<File>empty())
                .subscribe(file -> {

                    Log.i(TAG, file.getAbsolutePath());

                    int[] thumbWH = computeSize( file );

                    sb.append( String.format( "压缩后参数：%d*%d, %dk",  thumbWH[0],thumbWH[1] ,file.length() >> 10) );

                    viewDataBinding.imgText.setText( sb.toString() );
                    Uri mUri =  Uri.fromFile( file );

                    Glide.with( this )
                         .load( mUri )
                         .into( viewDataBinding.image );


                    //goCheckPicture(mUri.toString());

                });
        addSubscription( mDispo );

    }

    private <T> void withLs(final File photos) {
        Luban.with(this)
                .load(photos)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .setFocusAlpha(false)
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setRenameListener(new OnRenameListener() {
                    @Override
                    public String rename(String filePath) {
                        try {
                            MessageDigest md = MessageDigest.getInstance("MD5");
                            md.update(filePath.getBytes());
                            return new BigInteger(1, md.digest()).toString(32);
                        } catch (NoSuchAlgorithmException e) {
                            e.printStackTrace();
                        }
                        return "";
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() { }

                    @Override
                    public void onSuccess(File file)
                    {
                        Log.i(TAG, file.getAbsolutePath());

                        Uri mUri =  Uri.fromFile( file );
                        goCheckPicture(mUri.toString());

                    }

                    @Override
                    public void onError(Throwable e) { }
                }).launch();
    }

    private String getPath()
    {
        String path = Environment.getExternalStorageDirectory() + "/Download/image/";
        File file = new File(path);
        if (file.mkdirs())
        {
            return path;
        }
        return path;
    }


    /**
     * 获取 图片 尺寸
     * @param srcImg
     * @return
     */
    private int[] computeSize(File srcImg)
    {
        int[] size = new int[2];

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inSampleSize = 1;

        BitmapFactory.decodeFile(srcImg.getAbsolutePath(), options);
        size[0] = options.outWidth;
        size[1] = options.outHeight;

        return size;
    }

}
